//
//  CityChoosenViewController.m
//  DaoZiJinFu
//
//  Created by woker on 16/7/1.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "CityChoosenViewController.h"

@interface CityChoosenViewController ()

@end

@implementation CityChoosenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTitleView:@"选择城市"];
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    
    _dataList = [NSMutableArray array];
    _searchList = [NSMutableArray array];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
    NSDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
//    _dataList = [data objectForKey:@"data"];
//    NSLog(@"%@",data);
    
    NSMutableArray *cityArr = [NSMutableArray array];
    
    for (NSString *str in [data allKeys]) {
        NSDictionary *province = data[str];
//        NSLog(@"%@",[province  allKeys]);
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        for (NSString *str1 in [province allKeys]) {
            NSDictionary *dic = province[str1];
            
            NSMutableArray *arr = [NSMutableArray array];
            
            for (NSDictionary *str2 in [dic allKeys]) {
                NSDictionary *city = dic[str2];
                [arr addObjectsFromArray:[city allKeys]];
//                NSLog(@"%@",[city allKeys]);
            }
            
            [dict setValue:arr forKey:[[province allKeys] lastObject]];
        }
        [cityArr addObject:dict];
    }
    
    // 沙盒的目录
    NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    //得到文件绝对路径
    NSString *filePath = [[documentPath objectAtIndex:0] stringByAppendingPathComponent:@"City.plist"];
//    NSLog(@"%@",filePath);
    //写入文件
    [@{@"data":cityArr} writeToFile:filePath atomically:YES];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.sectionIndexColor = ORANGECOLOR;
    _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    _tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
    
    //创建UISearchController
    _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //设置代理
    _searchController.delegate = self;
    _searchController.searchResultsUpdater= self;
    //设置UISearchController的显示属性，以下3个属性默认为YES
    _searchController.dimsBackgroundDuringPresentation = NO;
    _searchController.obscuresBackgroundDuringPresentation = NO;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    
    _searchController.searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44.0);
    _searchController.searchBar.placeholder = @"请输入城市名查询";
    _searchController.searchBar.barTintColor = BACKGROUND_COLOR;
    _searchController.searchBar.delegate = self;
    
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = _searchController.searchBar;
    
    [self.view addSubview:_tableView];
}

//设置区域的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return [self.searchList count];
    }else{
        NSDictionary *dic = _dataList[section];
        NSArray *arr = dic[@"city"];
        return arr.count;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchController.active) {
        return 1;
    } else {
        return _dataList.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.searchController.active) {
        return 1;
    } else {
        return 20;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.searchController.active) {
        return nil;
    } else {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = BACKGROUND_COLOR;
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, SCREEN_WIDTH, 20)];
//        lab.text = _dataList[section][@"fir"];
        [view addSubview:lab];
        return view;
    }
}

//返回单元格内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *flag = @"citycell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
    if (cell == nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag];
    }
    if (self.searchController.active) {
        [cell.textLabel setText:self.searchList[indexPath.row]];
    }
    else{
        [cell.textLabel setText:[self.dataList[indexPath.section] objectForKey:@"city"][indexPath.row]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.searchController.active) {
        _cityStr = _dataList[indexPath.section][@"city"][indexPath.row];
    } else {
        _cityStr = _searchList[indexPath.row];
    }
    self.searchController.active = NO;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"chooseCityNotification" object:self userInfo:@{@"city":_cityStr}];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (!self.searchController.active) {
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in _dataList) {
            [arr addObject:dic[@"fir"]];
        }
        return arr;
    } else {
        return nil;
    }
}

#pragma mark - UISearchControllerDelegate代理
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    if (self.searchList!= nil) {
        [self.searchList removeAllObjects];
    }
    
    for (NSDictionary *dic in _dataList) {
        NSArray *arr = dic[@"city"];
        [_searchList addObjectsFromArray:[arr filteredArrayUsingPredicate:preicate]];
    }
    
    //刷新表格
    [self.tableView reloadData];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    for(UIView *view in [searchBar.subviews[0] subviews])
    {
        if([view isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)view;
            [btn setTitle:@"取消" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        }
    }
}

- (void)leftBarItemOnClick:(id)sender {
    _searchController.active = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

@end
